//https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
package codeRandomThoughts.Test1047删除字符串中的所有相邻重复项;

import java.util.Arrays;
import java.util.Stack;

/**
 * 两种方法
 * 用栈
 * 用双指针
 */
public class Solution3 {

    public String removeDuplicates(String s) {
        Stack<Character> stack = new Stack<>();
        char[] str = s.toCharArray();
        for (char c : str) {
            if (!stack.isEmpty() && stack.peek() == c) {
                stack.pop();
            } else {
                stack.push(c);
            }
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }

        sb.reverse();
        return sb.toString();
    }

    //双指针?二刷还是忘记
    public String removeDuplicates2(String s) {
        int slow = -1;
        char[] str = s.toCharArray();
        for (int fast = 0; fast < str.length; fast++) {
            if (slow > -1 && str[slow] == str[fast]) {
                slow--;
            } else {
                slow++;
                str[slow] = str[fast];
            }
        }

        //左闭右开
        char[] res = Arrays.copyOfRange(str, 0, slow + 1);
        return new String(res);
    }
}
